import base64
import json
from django.http import HttpResponse
from rest_framework.views import APIView
from captcha.views import CaptchaStore, captcha_image
from django.conf import settings
from rest_framework.exceptions import APIException
from django.utils import timezone


# 生成验证码
class CaptchaAPIView(APIView):

    def get(self, request):
        hash_key = CaptchaStore.generate_key()
        try:
            # 获取图片id
            # id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id
            image = captcha_image(request, hash_key)
            # 将图片转换为base64
            image_base = 'data:image/png;base64,%s' % base64.b64encode(image.content).decode('utf-8')

            json_data = json.dumps(
                {'code': 200, 'msg': 'ok', 'data': {'captcha_id': hash_key, 'captcha_image': image_base}})
            # 批量删除过期验证码
            CaptchaStore.remove_expired()
        except:
            json_data = None

        return HttpResponse(json_data, content_type="application/json")


# 验证验证码
def validate_captcha(captcha_id, captcha):
    # 判断长度
    if not captcha_id or not captcha or int(settings.CAPTCHA_LENGTH) != len(captcha):
        raise APIException('验证码错误！', code=1001)
    # 验证码转小写字母
    try:
        captcha = captcha.lower()
    except:
        raise APIException('验证码错误！', code=1001)
    # 数据库里查询验证码
    try:
        captcha_obj = CaptchaStore.objects.get(hashkey=captcha_id)
    except:
        raise APIException('验证码错误！', code=1001)
    # 如果不存在或者验证码不匹配
    if captcha_obj.response != captcha:
        raise APIException('验证码错误！', code=1001)
    # 验证是否过期
    if timezone.now() > captcha_obj.expiration:
        raise APIException('验证码过期！', code=1002)

    return True
